Skip to content

Mark inferred loop facts in errors, and hint to state a loop invariant - #560

Open
CatarinaGamboa wants to merge 2 commits into
perf/547-loop-costfrom
feat/554-mark-inferred-facts
Open

CatarinaGamboa wants to merge 2 commits into
perf/547-loop-costfrom
feat/554-mark-inferred-facts

Conversation

@CatarinaGamboa

@CatarinaGamboa CatarinaGamboa commented Nov 24, 2026 •

Copy link
Copy Markdown
Collaborator

Closes #554. Part of #548 (PM decisions in its comments) and the loop invariant plan #542.

Stacked on #556 (base perf/547-loop-cost). Retarget to main once #556 merges.

Part 1: inferred facts are marked in the diagnostic data

The terminal/hover message does not change. Inferred facts stay in Found as ordinary facts.

RefinementError.getInferredFacts() returns one InferredFacts per value in Found's original chain that inference gave facts to:

record InferredFacts(String variable, List<Expression> facts, SourcePosition loop, Point point)
enum Point { ITERATION_START, ITERATION_END, AFTER_LOOP }
  • variable is the internal name of the binder, e.g. #i_5. error.getDisplayNames().get(variable) gives i@46#1, the name the panel already shows.
  • facts are the conjuncts of that binder's refinement that inference added, e.g. i@46#1 >= i@45. Each one is equal to a conjunct of the binder's refinement in the Original step, so the panel can match them.
  • loop is the loop's position, which gives its line and lets the panel link to it.
  • point says where in the loop the facts hold:

Facts are recorded on the VariableInstance when LoopInvariants adds them. VCChecker then keeps those that are still conjuncts of a binder in the error's original chain, for binders linked to the terms of expected (the same linking as Found's counterexample filter). Invariants of unrelated loop variables are not listed.

Why this shape suits vscode-liquidjava#209.

  • Panel step. The panel can group the entries by loop and point and render one step before the simplification steps, e.g. "Inferred for the loop at line 46 (holds on every iteration): i@46#1 >= i@45". AFTER_LOOP would read "holds after the loop".
  • Name explanation. Each entry ties a display name (i@46#1) to its loop line and point. That is what the panel needs to explain a loop-start name, e.g. "the value of i at the start of an iteration of the loop at line 46".

The DTO is left to #209. A sketch:

record InferredFactsDTO(String variable, List<String> facts, SourcePositionDTO loop, String point) // point: "iteration-start" | "iteration-end" | "after-loop"
// variable and facts are formatted with error.getDisplayNames(), as VCImplicationDTO does

Part 2: hint to state a loop invariant (prototype)

The hint is added when an error in a loop body is finally reported (not on trial checks) and all of these hold:

  1. The counterexample's first variable that an enclosing loop changes is an int local declared without @Refinement. As with inference, fields and parameters are out of scope.
  2. Expected mentions that variable.
  3. Expected holds on the first iteration, i.e. with the loop-head values equal to the values before the loop. If it fails even then, forgetting is not the cause.
  4. If expected can be rewritten for the variable (one value of it, plus variables the code can name and the loop does not write), the refinement is suggested, but only if it holds before the loop. Otherwise there is no hint. If expected cannot be rewritten, there is a general hint with no concrete suggestion.

Text: `left` changes in the loop at line 8, and LiquidJava only keeps what holds for it on every iteration. If `left >= 0` should hold on every iteration, state it on the declaration: `@Refinement("_ >= 0") int left = 10;`. A for-init variable gets for (@Refinement("_ >= 0") int i = 0; ...). The hint's kind is LOOP_INVARIANT, and "line N" is a SourceReference to the loop.

Before / after

The message, snippet and counterexample are identical before and after. The only change is the added hint, which starts with "X changes in the loop at line N, and LiquidJava only keeps what holds for it on every iteration." The table shows the rest of the hint. "After following the hint" is the verifier's result once the suggested refinement is added.

Program Message (before = after) Hint added After following the hint Verdict
#537 for (int i = 0; i < 10; i++) use(i), the while (total < 1024) accumulator, and the buffer loop with if (n < 0) break; passes none n/a No error left, so no hint (#551 fixed these)
buffer loop without the n < 0 check (total += n, read(buf, total, ...) needs off >= 0) found `total < limit` but expected `total >= 0` · cex total == -1 && limit == 0 If total >= 0 should hold…: @Refinement("_ >= 0") int total = 0; error moves to total += n Helps: points at the real cause (n may be negative)
countdown left = left - 3; wait(left) (_ >= 0), from 10 found `left@8#1 <= 10 && left@8#1 > 0 && left == left@8#1 - 3` but expected `left >= 0` · cex left == -1 && left@8#1 == 2 If left >= 0 …: @Refinement("_ >= 0") int left = 10; error moves to left = left - 3 Helps: real bug, localised to the update
retry with reset: sleep(delay) (_ > 0), delay = delay > 60 ? 1 : delay * 2 expected `delay > 0` but could not prove it · cex delay == 0 If delay > 0 …: @Refinement("_ > 0") int delay = 8; passes Helps: a correct program that inference cannot prove (the reset breaks delay >= 8)
two counters left--; done++; progress(n, done) (done <= n) found `done@9 >= 0 && n >= 0 && left <= n && left >= 0 && left > 0 && done == done@9 + 1` but expected `done <= n` · cex n == 1 && done == 2 && done@9 == 1 && left == 1 If done <= n …: @Refinement("_ <= n") int done = 0; error moves to done++ Misleads: the program is correct, but it needs left + done == n, which no single declaration can state. The suggestion is a dead end
sum total = total + read() (unrefined read), report(total) found `total == total@10 + #read_result` but expected `total >= 0` · cex total == -1 && total@10 == -1 && #read_result == 0 none (fails on the first iteration) n/a Correct to stay silent: the fix is read's refinement
index for (i = 0; i <= size; i++) get(size, i) (_ < size) found `size >= 0 && i <= size && i >= 0` but expected `i >= 0 && i < size` · cex size == 0 && i == 0 none (fails on the first iteration) n/a Correct: an off-by-one the loop does not cause
budget budget = budget - price() (unrefined), pay(budget) found `budget@10#1 > 0 && budget == budget@10#1 - #price_result` but expected `budget >= 0` · cex budget == -1 && budget@10#1 == 1 && #price_result == 2 none (fails on the first iteration) n/a Correct
int shifted = i - 1; percent(shifted) in while (i < n) found `i >= 0 && i < n && shifted == i - 1` but expected `shifted >= 0 && shifted <= 100` none n/a Correct (fails on the first iteration)
while (p < 100) p = p + 30; percent(p) after the loop found `p >= 0 && !(p < 100)` but expected `p >= 0 && p <= 100` none (not in a loop) n/a Out of scope. The Found facts are marked AFTER_LOOP
ErrorLoopUnprovedInvariant total = total + read(); nonNeg(total) found `total == total@16 + #read_result` but expected `total >= 0` none (fails on the first iteration) n/a Correct
ErrorLoopInvariants decrementing, for (int i = 10; i > -5; i--) use(i) found `i > -5 && i <= 10 && i >= -5` but expected `i >= 0` · cex i == -1 If i >= 0 …: for (@Refinement("_ >= 0") int i = 10; ...) error moves to i-- Real bug. Acceptable: the "should" wording and the error moving to i-- show it does not hold
ErrorLoopInvariants resetInBody / decreasedOnSomePath / decreasedBeforeContinue / decreasedBeforeContinueInFor / decreasedInInnerLoop (lines 25, 35, 55, 71, 78) found `i < 10 && i <= 10` but expected `i >= 0` (35: found `i < 10` ) · cex i == -1 If i >= 0 …: @Refinement("_ >= 0") int i = 0; (71: the for (…; ...) form) error moves to the assignment that breaks it (i = -1, i = i - 2, …) Real bugs. Acceptable: following it localises the bug
ErrorLoopInvariants boundNotKept i = i + 3; atMostTen(i) found `i@46#1 >= 0 && i@46#1 < 10 && i == i@46#1 + 3` but expected `i <= 10` · cex i == 11 && i@46#1 == 8 If i <= 10 …: @Refinement("_ <= 10") int i = 0; error moves to i = i + 3 Real bug. Acceptable
ErrorLoopCondition incrementInBody i++; lessThanTen(i) found `i@77#1 >= 0 && i@77#1 <= 10 && i@77#1 < 10 && i == i@77#1 + 1` but expected `i < 10` If i < 10 …: @Refinement("_ < 10") int i = 0; error moves to i++ Real bug. Acceptable
ErrorLoopCondition laterIteration (int k = read(), k > 0 needed) / innerLoopInDoWhile (int n = 0, n > 0 needed) unchanged none: the suggestion would not hold before the loop n/a Correct to stay silent. Without the "holds before the loop" filter, both got a wrong suggestion
ErrorLoopCondition laterIterationFromKnownStart (@Refinement("_ > 0") int y = x - 1) unchanged none: expected is about y, not x n/a Correct. Before the "mentions the variable" filter it got a general hint that pointed at the wrong variable
a for-init variable already refined, for (@Refinement("_ >= 0") int i = 10; …; i--) unchanged none (already refined) n/a Correct
all other loop fixtures (ErrorEmptyLoopBody, ErrorLoopExitFacts, the ErrorLoopState* fixtures, ErrorLoopPostState, ErrorLoopFreshReceivers, and the classes/* fixtures with loops) unchanged none n/a Only refinement errors get the hint

Honest verdict on the hint

  • In study-like code it rarely fires. Infer loop invariants for the int locals a loop changes (Houdini) #551 already proves the common counters and accumulators, so when an error remains it is mostly a real bug. Then the suggestion does not fix anything: it moves the error to the assignment that breaks the invariant. That localises the bug well. The "If … should hold" wording keeps it from claiming the program is right.
  • It fully fixes a correct program that inference cannot prove (the retry loop with a reset).
  • It misleads when the needed invariant is relational between two variables (the left/done counters). The suggestion is a dead end there, and I found no cheap way to detect that.
  • The first-iteration and before-loop checks removed every wrong suggestion I saw in the fixtures (k = read(), n = 0 in the do-while, the y/x case).
  • The general hint (no concrete refinement) never fired in these examples after the filters. It only fires when expected also mentions a value the code cannot name.

On balance it helps more than it misleads on these examples. Still, its main value on real bugs is to localise them, not to fix them. Your call whether that is worth a hint.

Tests

  • TestLoopInvariantDiagnostics:
    • ITERATION_START facts and their loop (ErrorLoopInvariants:48).
    • AFTER_LOOP facts (new pastTheBound case in ErrorLoopExitFacts).
    • The hint text and its line reference (ErrorLoopInvariants:25).
    • No hint when expected fails on the first iteration (ErrorLoopUnprovedInvariant).
    • No marked facts for values expected does not depend on (ErrorLoopUnprovedInvariant).
  • The full suite passes locally.
  • Private study check against verify-cur-redesign (55 variants): verdicts and messages are identical. No shipped task gets the hint.

🤖 Generated with Claude Code

CatarinaGamboa and others added 2 commits November 24, 2026 12:58
A refinement error now lists, for clients, the facts of Found that loop
invariant inference added, with the value they are about, the loop and
where in it they hold (start of an iteration, end of the body, after the
loop). The message text does not change.

A prototype hint is added to an error in a loop whose counterexample is
about an unrefined int local the loop changes, when expected holds on
the first iteration: it says the loop only keeps what holds on every
iteration, and suggests expected as a refinement of the declaration when
it can be written for the variable and holds before the loop.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 1

Codex (codex exec) reviewed the diff for soundness and correctness and ran reproducers. It reported no crash, no changed verdict, and no leftover path-variable or context state from the hint's checks. Nested-loop and after-loop marks were correct.

  1. P2: the hint suggests an invariant the loop violates. In ErrorLoopInvariants.boundNotKept, the hint suggests @Refinement("_ <= 10") int i = 0;, but i = i + 3 takes i from 8 to 11. Applying the suggestion moves the error to i = i + 3.
    • Not changed. This is the known real-bug case, and the PR body lists it. Checking that the update keeps the refinement would need a body re-check per error, which is what Houdini already does for its candidates. The hint is worded "If … should hold on every iteration", and following it points at the assignment that breaks it, which is the bug. The PM decides whether that is useful enough.
  2. P3: getInferredFacts() lists facts that have nothing to do with the error. For ErrorLoopUnprovedInvariant (an error about total), it listed i's invariants from the original chain.
    • Fixed. Only binders linked to the terms of expected are kept, the same linking that Found's counterexample filter uses. Added the test factsInferredForValuesExpectedDoesNotDependOnAreNotMarked.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Clean-code review

Audit with the clean-code-principles skill, on git diff perf/547-loop-cost...HEAD.

  • LoopInvariantHint.java [core-dry]: VariableFormatter.withoutInstance(name).equals(variable) was repeated three times, and the loop's CtVariableWrite scan twice. Applied: extracted isValueOf and writes.
  • LoopInvariantHint.isRefined and OriginNotes.isRefined [core-dry / name-searchable]: both spell out "liquidjava.specification.Refinement", and so does TypeChecker. Left: this matches the existing code. A shared constant would be a separate cleanup.
  • LoopInvariants.holdsBefore [func-no-side-effects / core-law-of-demeter]: it swaps checker.vcChecker's path variables to check what holds before the loop. Left: they are restored in finally, and LoopInvariants already works through the checker in the same way for its other proofs.
  • RefinementError.setInferredFacts [core-encapsulation]: a setter instead of a constructor argument. Left: it follows how OriginNotes adds message notes after construction, and avoids changing the constructor that other callers use.
  • LoopInvariantHint.addTo [func-single-purpose]: it picks the variable and also applies the filters. Left: it is short and each filter is commented in the method's javadoc.

No SRP or layering issues: inference records the facts, VCChecker selects them for an error, and the hint is in its own class, called once where the error is finally reported.

@CatarinaGamboa

Copy link
Copy Markdown
Collaborator Author

Codex review, round 2

Codex reviewed the whole diff again, including the new linking filter in VCChecker.inferredFactsOf and LoopInvariantHint, and tried scratch programs. It found no remaining soundness or correctness bugs. It did not re-report the round-1 point that was left unchanged: the hint can suggest a refinement the loop does not keep, which happens on real bugs. The review loop ends here.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant